import 'dart:async';
import 'package:flutter/material.dart';
import 'package:xview/utils/dimension.dart';

_onClick(index){}

class XTabs extends StatefulWidget {
  List list;
  double itemWidth;
  bool scrollable;
  Function onClick;
  double height;

  XTabs({
    required this.list,
    this.itemWidth = 60,
    this.scrollable = true,
    this.onClick = _onClick,
    this.height = 44,
  });

  @override
  State<StatefulWidget> createState() {
    return _xTabsState();
  }
}

class _xTabsState extends State<XTabs> {
  late List listKeys = [];
  late ScrollController listViewController = new ScrollController();
  double scrollLeft = 0;
  late double left = widget.itemWidth/2 - 8;
  int moveDuration = 300;
  GlobalKey listViewKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    listKeys = [];
    for(var idx in widget.list){
      GlobalKey _anchorKey = GlobalKey();
      listKeys.add(_anchorKey);
    }

    return Container(
      width: Dimension(context).toVw(100),
      height: Dimension(context).toPx(widget.height),
      // padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(15)),
      color: Colors.white,
      child: Stack(
        children: [
          widget.scrollable?ListView.builder(
            key: listViewKey,
            controller: listViewController,
            itemCount: widget.list.length,
            scrollDirection: Axis.horizontal,
            itemExtent: Dimension(context).toPx(widget.itemWidth),
            itemBuilder: (ctx,index){
              return GestureDetector(
                onTap: (){
                  // print(index);
                  move(index);
                  widget.onClick(index);
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  key: listKeys[index],
                  height: Dimension(context).toPx(widget.height),
                  padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(10)),
                  constraints: BoxConstraints(
                    minWidth: Dimension(context).toPx(60),
                  ),
                  child: Align(
                    alignment: Alignment.center,
                    child: Text('${widget.list[index]}',style: TextStyle(color: Color(0xff303133),fontSize: Dimension(context).toPx(15))),
                  ),
                ),
              );
            },
          ):Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: renderView(),
          ),
          AnimatedPositioned(
            bottom: 3,
            left: left,
            duration: Duration(milliseconds: 300),
            child: Container(
              width: Dimension(context).toPx(16),
              height: Dimension(context).toPx(4),
              decoration: BoxDecoration(
                color: Color(0xff1661ff),
                borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(4)))
              ),
            ),
          )
        ],
      )
    );
  }


  move(index){
    double _dpWidth = MediaQuery.of(context).size.width; //窗口宽度
    // 让活动的tab处于屏幕的中间位置
    RenderBox renderBox = listKeys[index].currentContext?.findRenderObject() as RenderBox;
    var offset = renderBox.localToGlobal(Offset.zero);
    var size = renderBox.size;
    //判断横轴移动方向
    var tabWidth = size.width; // 活动item的宽度
    var offsetLeft = offset.dx; // 活动item的左边到tabs组件左边的距离
    double listViewWidth = Dimension(context).toPx(widget.itemWidth) * widget.list.length; //计算listview总长
    // 将活动的tabs-item移动到屏幕正中间
    var _scrollLeft = listViewController.offset + offsetLeft - (_dpWidth - tabWidth) / 2;
    // print('${listViewController.offset + _dpWidth} ${_scrollLeft + _dpWidth} ${listViewWidth} ${_dpWidth}');
    scrollLeft = _scrollLeft < 0 ? 0 : _scrollLeft;

    //移动滑块
    //当listViewController.offset + _dpWidth < listViewWidth且_scrollLeft + _dpWidth > listViewWidth时，还会发生移动，移动到无法移动时则会停止，此时要在移动结束后计算位置
    // 当前活动item的中点点到左边的距离减去滑块宽度的一半，即可得到滑块所需的移动距离
    if(scrollLeft + _dpWidth > listViewWidth && listViewController.offset + _dpWidth < listViewWidth){
      listViewController.animateTo(scrollLeft,duration: Duration(milliseconds: 300),curve: Curves.ease);
      Timer(Duration(milliseconds: 300),(){
        RenderBox renderBoxNow = listKeys[index].currentContext?.findRenderObject() as RenderBox;
        var offsetNow = renderBoxNow.localToGlobal(Offset.zero);
        setState(() {
          left = tabWidth / 2 - 8 + offsetNow.dx;
        });
      });
    }else if(scrollLeft + _dpWidth > listViewWidth && listViewController.offset + _dpWidth >= listViewWidth){
      listViewController.animateTo(scrollLeft,duration: Duration(milliseconds: moveDuration),curve: Curves.ease);
      setState(() {
        left = tabWidth / 2 - 8 + offset.dx;
      });
    }else if(scrollLeft + _dpWidth <= listViewWidth){
      listViewController.animateTo(scrollLeft,duration: Duration(milliseconds: moveDuration),curve: Curves.ease);
      setState(() {
        left = tabWidth / 2 - 8 + offset.dx + listViewController.offset - scrollLeft;
      });
    }
  }

  move2(index){
    RenderBox renderBox = listKeys[index].currentContext?.findRenderObject() as RenderBox;
    var offset = renderBox.localToGlobal(Offset.zero);
    var size = renderBox.size;
    setState(() {
      left = size.width / 2 - 8 + offset.dx;
    });
  }

  renderView(){
    // 不滑动模式下的item
    List<Widget> view = [];
    for(var index = 0;index < widget.list.length;index++){
      view.add(GestureDetector(
        onTap: (){
          move2(index);
          widget.onClick(index);
        },
        behavior: HitTestBehavior.opaque,
        child: Container(
          key: listKeys[index],
          width: Dimension(context).toPx(widget.itemWidth),
          height: Dimension(context).toPx(widget.height),
          padding: EdgeInsets.symmetric(horizontal: Dimension(context).toPx(10)),
          constraints: BoxConstraints(
            minWidth: Dimension(context).toPx(60),
          ),
          child: Align(
            alignment: Alignment.center,
            child: Text('${widget.list[index]}',style: TextStyle(color: Color(0xff303133),fontSize: Dimension(context).toPx(15))),
          ),
        ),
      ));
    }
    return view;
  }

  @override
  void dispose() {
    super.dispose();
  }
}
